﻿using System.Configuration;
using System.Reflection;
using Autofac;
using Autofac.Configuration;
using Autofac.Integration.Mvc;
using MovieDB.Entities;

namespace MovieDB.AutofacRegistration
{
    public class AutofacRegister
    {
        public static void RegisterAllComponents(ContainerBuilder containerBuilder, Assembly assembly)
        {
            containerBuilder.RegisterModule(new AutofacWebTypesModule());
            
            RegisterControllers(containerBuilder, assembly);
            RegisterModelBinder(containerBuilder, assembly);
            RegisterServices(containerBuilder);
            RegisterManual(containerBuilder);
            //RegisterComponentsFromXml(containerBuilder);
        }


        private static void RegisterControllers(ContainerBuilder containerBuilder, Assembly assembly)
        {
            containerBuilder.RegisterControllers(assembly).InstancePerHttpRequest();
        }

        private static void RegisterModelBinder(ContainerBuilder containerBuilder, Assembly assembly)
        {
            containerBuilder.RegisterModelBinders(assembly).InstancePerHttpRequest();
            containerBuilder.RegisterModelBinderProvider();
        }

        private static void RegisterServices(ContainerBuilder containerBuilder)
        {
            string[] assembliesToRegister = new[]
                                            {
                                                RegisterHelper.Services,
                                                RegisterHelper.Repositories,
                                                RegisterHelper.Factories,
                                                RegisterHelper.Mapping
                                            };

            RegisterAssemblies(containerBuilder, assembliesToRegister);
        }

        private static void RegisterManual(ContainerBuilder containerBuilder)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MovieDBEntities"].ConnectionString;
            containerBuilder.Register(x => new MovieContext(connectionString)).As<IContext>().InstancePerHttpRequest();
        }

        private static void RegisterComponentsFromXml(ContainerBuilder containerBuilder)
        {
            containerBuilder.RegisterModule(new ConfigurationSettingsReader("autofac"));
        }

        private static void RegisterAssemblies(ContainerBuilder containerBuilder, params string[] assemblyNames)
        {
            foreach (var assemblyName in assemblyNames)
            {
                var assembly = Assembly.Load(assemblyName);
                containerBuilder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces().InstancePerHttpRequest();
            }
        }
    }
}